package uns.fit.gis.ui;

import java.io.IOException;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;

import uns.fit.gis.MapDrawer;
import uns.fit.gis.Util;
import uns.fit.gis.mapdrawer.MapCanvas;

public class RouteCanvas extends Canvas implements CommandListener {
	private Sprite turningSprite;
	private Command backCommand;
	private MapDrawer midlet;
	private static Font font;
	
	public RouteCanvas(String title, MapDrawer midlet) {
		this.midlet = midlet;
		backCommand = new Command("Quay lại", Command.BACK, 1);
		addCommand(backCommand);
		setCommandListener(this);
		font = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL);
			
		try {
			turningSprite = new Sprite(Image.createImage("/turnicon.png"), 16, 16);
		}
		catch(IOException exception) {
			exception.printStackTrace();
		}
	}
	
	protected void paint(Graphics g) {
		g.setFont(font);
		if(MapCanvas.alg != null) {
			String route = MapCanvas.alg.routeToString();
			g.setColor(221, 238, 187);
			g.fillRect(0, 0, getWidth(), getHeight());
			g.setColor(0, 0, 0);
			if(route != null) {
				int x = 20;
				int y = 20;
				g.drawString("Quãng đường tổng cộng: " + MapCanvas.alg.getTotalLength() + "m", x, y, Graphics.TOP | Graphics.LEFT);
				String[] subroutes = Util.split(route, "\n");
				y += 20;
				g.drawLine(x, y, getWidth() - 20, y);
				y += 20;
				for(int i = 0; i < subroutes.length; i ++){
					if(subroutes[i].equalsIgnoreCase(Util.GO_STRAIGHT)) {
						turningSprite.setFrame(1);
						turningSprite.setPosition(x, y);
						turningSprite.paint(g);
					}
					else if(subroutes[i].equalsIgnoreCase(Util.TURN_LEFT)) {
						turningSprite.setFrame(0);
						turningSprite.setPosition(x, y);
						turningSprite.paint(g);
					}
					else if(subroutes[i].equalsIgnoreCase(Util.TURN_RIGHT)) {
						turningSprite.setFrame(2);
						turningSprite.setPosition(x, y);
						turningSprite.paint(g);
					}
					else {
						Util.drawText(g, subroutes[i], x, y, 0, 0);
						//g.drawString(subroutes[i], x, y, Graphics.TOP | Graphics.LEFT);
					}
					y += 20;
				}
			}
		}
	}
	
	public void commandAction(Command command, Displayable displayable) {
		if(command == backCommand) {
			midlet.showMapCanvas();
		}
	}
}
